<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/1/8 0008
 * Time: 上午 9:40
 */

namespace app\admin\validate;


use app\admin\model\UserModel;
use think\Validate;

class UserValidate extends Validate
{
    public $userData;
    protected $rule = [
        "username|用户名" => "require|length:2,10",
        "password|密码" => "require|length:6,13",
        "repass|确认密码" => "require|confirm:password",
        "__token__" => "token"
    ];

    /**
     * 登入验证
     * @return UserValidate
     */
    public function sceneCode()
    {
        return $this->only(["username","password","code"])
            ->append("username","userNotExists")
            ->append("password","passwordIsCorrect")
            ->append("code","captcha");
    }

    public function sceneLogin()
    {
        return $this->only(["username","password"])
            ->append("username","userNotExists")
            ->append("password","passwordIsCorrect");
    }

    /**
     * 验证用户是否存在 Login
     * @param $value
     * @return bool|string
     */
    protected function userNotExists($value)
    {
        $result = UserModel::userExists($value);

        if (is_string($result)) return "该账户已被冻结!";

        if (is_null($result)) return "用户不存在";

        $this->userData = $result;
        return true;
    }


    /**
     * 验证密码
     * @param $value
     * @return bool|string
     */
    protected function passwordIsCorrect($value)
    {
        $userData = $this->userData;
        $password = md5($value . $userData["salt"]);
        if ($userData["password"] !== $password) {
            return "密码有误";
        }
        return true;
    }
}